﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
//using www.SService;
using www.Controllerss;
using www.Core.Contract.DataContract;

namespace www.Admin
{
    public partial class BrowerPhoto : System.Web.UI.Page
    {
        #region Value

        private readonly ObjectCache _cache = MemoryCache.Default;
        //private readonly HyServicesClient _service = new HyServicesClient();
        private readonly LanguageController _languageController=new LanguageController();
        private readonly LoginController _loginController=new LoginController();
        private readonly MenuMemberController _menuMemberController=new MenuMemberController();
        private readonly MenuController _menuController=new MenuController();
        private readonly CategoryController _categoryController=new CategoryController();
        private readonly PhotoController _photoController=new PhotoController();
        static long _id = 0;
        private static int iLanguageCode;

        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Cache["Language"] == null)
            {
                var lLanguage = _languageController.GetLanguageDataContracts();
                if (lLanguage.Any())
                    Cache.Insert("Language", lLanguage.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }
            if (_cache["UserClient"] == null)
            {
                var lData = _loginController.GetAllClientUser();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(27);
                    _cache.Set("UserClient", lData.ToList(), policy);
                }
            }

            if (!IsPostBack)
            {
                var lLanguages = (List<RelaxLanguageDataContract>)Cache["Language"];
                if (lLanguages != null)
                {
                    var lReturn = lLanguages.Where(l => l.Type == 1);
                    Addlist(lReturn);
                }
                LoadCategory();
                LoadData();
            }
        }
        #endregion

        #region Event
        protected void ddlgroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }

        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_PostConfide.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var il = e.CommandArgument.ToString().Split('_');
                if (il.Length <= 1)
                    return;
                _id = Convert.ToInt32(il[0]);
                iLanguageCode = Convert.ToInt32(il[1]);
                var lData = (List<RelaxPhotoDataContract>)_cache["Photo"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == iLanguageCode);
                if (first == null)
                    return;
                if (e.CommandName == "cmd_Detail")
                {
                    frmDetail.DataSource = new List<RelaxPhotoDataContract> { first };
                    frmDetail.DataBind();
                    pncontrols.Visible = true;
                    pnviews.Visible = false;
                }
                else if (e.CommandName == "cmd_delete")
                {

                    DeleteLanguage(iLanguageCode);
                    Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                    lData.Remove(first);
                    _cache["Photo"] = lData;
                    LoadData();
                    Message("Xóa Thành Công");
                    _id = 0;

                }
            }
            catch (Exception)
            {

            }
        }

        protected void grid_PostConfide_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var userId = ((Label)e.Row.FindControl("lblUserId")).Text;
                if (!string.IsNullOrEmpty(userId))
                {
                    var lData = (List<RelaxLoginsDataContract>)_cache["UserClient"];
                    if (lData != null)
                    {
                        var first = lData.FirstOrDefault(p => p.Id == Convert.ToInt32(userId));
                        if (first != null)
                        {
                            var userName = (Label)e.Row.FindControl("lblUserName");
                            userName.Text = first.UserName;
                        }
                    }
                }
            }
        }

        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        #endregion

        #region Business
        private void LoadStaffMenu()
        {
            if (_cache["StaffMenu"] == null)
            {
                var lData = _menuMemberController.GetMenuMemberDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("StaffMenu", lData.ToList(), policy);
                }
            }
            if (_cache["Menu"] == null)
            {
                var lData = _menuController.GetMenuDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Menu", lData.ToList(), policy);
                }
            }
            if (_cache["Category"] == null)
            {
                var lData = _categoryController.GetCategoryDataContracts();
                var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                _cache.Set("Category", lData.ToList(), policy);
            }
        }
        private void LoadCategory()
        {
            LoadStaffMenu();
            var lMenuStaff = (List<RelaxMenuMemberDataContract>)_cache["StaffMenu"];
            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lCategory = (List<RelaxCategoryDataContract>)_cache["Category"];
            if (lMenu == null)
                return;
            if (lMenuStaff == null)
                return;
            if (lCategory == null)
                return;
            var lReturn = (from c in lCategory.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display)
                           join m in lMenu.Where(p => p.Languagecode == 1 && p.Active == Constant.Active.Display) on c.Id equals m.CategoryId
                           join s in lMenuStaff.Where(p => p.MemberId == Convert.ToInt32(Session["StaffId"]) && p.Active == Constant.Active.Display) on m.Id equals
                    s.MenuId
                           select new { c.Id, c.Name, c.Type }).ToList();
            var tmp = lReturn.ToList();
            foreach (var item in tmp)
            {
                var checkItem = lReturn.Where(p => p.Id == item.Id).ToList();
                if (checkItem.Count > 1)
                {
                    var first = checkItem.FirstOrDefault();
                    foreach (var item1 in checkItem)
                    {
                        lReturn.Remove(item1);
                    }
                    lReturn.Add(first);
                }
            }
            ddlCategory1.Items.Add(new ListItem("---Chọn---", "0"));
            var lParent = lReturn.Where(p => p.Type == 0).ToList();
            if (lParent.Any())
            {
                foreach (var item in lParent)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                    var lreturn1 = lCategory.Where(p => p.Type == item.Id && p.Languagecode == 1).ToList();
                    if (lreturn1.Any())
                    {
                        foreach (var item1 in lreturn1)
                        {
                            ddlCategory1.Items.Add(new ListItem("--" + item1.Name, item1.Id.ToString()));

                        }
                    }
                }
            }
            else
            {
                foreach (var item in lReturn)
                {
                    ddlCategory1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }
            }

        }
     
        private void Addlist(IEnumerable<RelaxLanguageDataContract> lLanguageDataContracts)
        {
            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Add(new ListItem("---Chọn---", "0"));
            foreach (var item in lLanguageDataContracts)
            {
                var items = new ListItem(item.Name, item.Id.ToString());
                ddlLanguage.Items.Add(items);
            }
        }

        private void Save()
        {
            try
            {

                var lData = (List<RelaxPhotoDataContract>)_cache["Photo"];

                var lUpdate = new List<RelaxPhotoDataContract>();
                if (lData == null)
                    return;
                var first =
                    lData.Where(
                        p => p.Id == _id && p.Languagecode == iLanguageCode).ToList();
                if (!first.Any())
                    return;
                foreach (var item in first)
                {
                    item.Active = 1;
                }

                lUpdate.Add(first.FirstOrDefault());

                if (_photoController.Update(lUpdate))
                {
                    var relaxPhotoDataContract = first.FirstOrDefault();
                    var url = string.Empty;
                    if(relaxPhotoDataContract!=null)
                        url = "http://relax2s.com/Home/PhotoDetail/" + (relaxPhotoDataContract.Languagecode == 1 ? "vi-VN" : relaxPhotoDataContract.Languagecode == 2 ? "en-US" : "zh-CN") + "/" + relaxPhotoDataContract.Id + "/" + relaxPhotoDataContract.Tag;
                    lblMessageLink.InnerHtml += "<div>" + url + "</div>";
                    //_xmlClass.WriteUrl();
                    _cache["Photo"] = lData;
                    Message("Sửa Thành Công !");
                    _id = 0;
                    iLanguageCode = 0;
                    pncontrols.Visible = false;
                    pnviews.Visible = true;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnviews.Visible = true;
            pncontrols.Visible = false;
            _id = 0;
            iLanguageCode = 0;
            LoadData();
        }
        private void DeleteLanguage(int iLanguagecode)
        {
            if (iLanguagecode <= 0) return;

            if (_id > 0)
            {
                _photoController.Delete(new List<long> { _id }, iLanguagecode);
            }

        }
        private void Delete()
        {
            try
            {
                if (grid_PostConfide.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_PostConfide.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_PostConfide.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_PostConfide.Rows[i].FindControl("lblId")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                if (_photoController.Delete(lAd, Convert.ToInt32(ddlLanguage.SelectedValue)))
                {
                    var lData = (List<RelaxPhotoDataContract>)_cache["Photo"];
                    if ((lData.Any()))
                    {
                        foreach (var id in lAd)
                        {
                            var first = lData.FirstOrDefault(p => p.Id == id && p.Languagecode == Convert.ToInt32(ddlLanguage.SelectedValue));
                            if (first != null)
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                                lData.Remove(first);
                            }
                            hang++;
                        }
                    }
                    if (hang != 0)
                    {
                        Message("Có " + hang + "bản ghi được Xóa Thành Công");
                    }
                    else
                    {
                        Message("Không có bản ghi nào được xóa !");
                    }
                    _cache["Photo"] = lData;
                    LoadData();
                }
            }
            catch { }
        }
        public void LoadData()
        {
            grid_PostConfide.DataSourceID = null;
            if (_cache["Photo"] == null)
            {
                var lData = _photoController.GePhotoDataContracts();
                if (lData.Any())
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(27) };
                    _cache.Set("Photo", lData.ToList(), policy);
                }
            }
            var lData1 = (List<RelaxPhotoDataContract>)_cache["Photo"];
            if (lData1 != null)
            {
                var lReturn = (from c in lData1.Where(p => p.Languagecode == Convert.ToInt32(ddlLanguage.SelectedValue) && p.CategoryId == Convert.ToInt32(string.IsNullOrEmpty(ddlCategory1.SelectedValue) ? "0" : ddlCategory1.SelectedValue) && p.Active == 2)
                               select new RelaxPhotoDataContract { Active = c.Active, Id = c.Id, Languagecode = c.Languagecode, Name = c.Name, Priority = c.Priority, Tag = c.Tag, Image = c.Image, Date = c.Date, Userid = c.Userid }).ToList();
                
                grid_PostConfide.DataSource = lReturn.ToList();
            }
            grid_PostConfide.DataBind();
        }


        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion
    }
}